 
package com.zdkj.subway.rca.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.subway.rca.entity.ViewCkOperatorsTicketRevenueClear;
import com.zdkj.subway.rca.mapper.ViewCkOperatorsTicketRevenueClearMapper;
import com.zdkj.subway.rca.service.ViewCkOperatorsTicketRevenueClearService;
import com.zdkj.subway.rca.util.LocalDateConverter;
import com.zdkj.subway.rca.util.LocalDateTimeConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * VIEW
 *
 * @author stw
 * @date 2020-12-16 11:00:18
 */
@Service
public class ViewCkOperatorsTicketRevenueClearServiceImpl extends ServiceImpl<ViewCkOperatorsTicketRevenueClearMapper, ViewCkOperatorsTicketRevenueClear> implements ViewCkOperatorsTicketRevenueClearService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ViewCkOperatorsTicketRevenueClearServiceImpl.class);
    @Override
    public List<ViewCkOperatorsTicketRevenueClear> listViewCkOperatorsTicketRevenueClear(String startDate, String endDate, String operators, String lineCode) {
        ViewCkOperatorsTicketRevenueClear viewCkOperatorsTicketRevenueClear = new ViewCkOperatorsTicketRevenueClear();
        viewCkOperatorsTicketRevenueClear.setBeginTime(LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        viewCkOperatorsTicketRevenueClear.setEndTime(LocalDate.parse(endDate, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        viewCkOperatorsTicketRevenueClear.setOperators(operators);
        viewCkOperatorsTicketRevenueClear.setLineCode(lineCode);
        QueryWrapper<ViewCkOperatorsTicketRevenueClear> queryWrappers = Wrappers.query(viewCkOperatorsTicketRevenueClear);
        queryWrappers.orderByAsc("OPERATORS");
        queryWrappers.orderByAsc("CAST(LINE_CODE AS SIGNED)");
        List<ViewCkOperatorsTicketRevenueClear> list = this.list(queryWrappers);
        List<ViewCkOperatorsTicketRevenueClear> listNew = new ArrayList<>();

        String operatorsName = null;
        for(ViewCkOperatorsTicketRevenueClear obj : list){
            if(!obj.getOperatorsName().equals(operatorsName) && operatorsName != null){
                ViewCkOperatorsTicketRevenueClear sum = getSum(operatorsName, list);
                listNew.add(sum);
            }
            operatorsName = obj.getOperatorsName();
            listNew.add(obj);
        }
        if(list.size() > 0) { //最后一个运营商
            ViewCkOperatorsTicketRevenueClear sum = getSum(operatorsName, list);
            listNew.add(sum);
        }

        ViewCkOperatorsTicketRevenueClear sumAll  = getSum("合计",list);
        sumAll.setLineName("--");
        listNew.add(sumAll);
        return listNew;
    }

    private ViewCkOperatorsTicketRevenueClear getSum(String operatorsName,List<ViewCkOperatorsTicketRevenueClear> list){
        ViewCkOperatorsTicketRevenueClear sumViewCkOperatorsTicketRevenueClear = new ViewCkOperatorsTicketRevenueClear();
        sumViewCkOperatorsTicketRevenueClear.setOperatorsName(operatorsName);
        sumViewCkOperatorsTicketRevenueClear.setLineName("小计");
        if("合计".equals(operatorsName)){
            sumViewCkOperatorsTicketRevenueClear.setOperators("合计");
        }

        BigDecimal receivableOnewayReceivedClean = new BigDecimal("0");
		BigDecimal returnOnewayReceivedClean = new BigDecimal("0");
		BigDecimal sumOnewayReceivedClean = new BigDecimal("0");
        BigDecimal countingTicket = new BigDecimal("0");
        BigDecimal dailyTicket = new BigDecimal("0");
        BigDecimal commemorativeTicket = new BigDecimal("0");
        BigDecimal cat = new BigDecimal("0");
        BigDecimal trafficCard = new BigDecimal("0");
        BigDecimal qrCodeTicket = new BigDecimal("0");
        BigDecimal faceTicketCcb = new BigDecimal("0");
        BigDecimal incomeSubtotal = new BigDecimal("0");

        for(ViewCkOperatorsTicketRevenueClear  obj : list){
            if(operatorsName.equals("合计") || operatorsName.equals(obj.getOperatorsName())){
                receivableOnewayReceivedClean = receivableOnewayReceivedClean.add(obj.getReceivableOnewayReceivedClean());
				returnOnewayReceivedClean = returnOnewayReceivedClean.add(obj.getReturnOnewayReceivedClean());
				sumOnewayReceivedClean = sumOnewayReceivedClean.add(obj.getSumOnewayReceivedClean());
                countingTicket = countingTicket.add(obj.getCountingTicket());
                dailyTicket = dailyTicket.add(obj.getDailyTicket());
                commemorativeTicket = commemorativeTicket.add(obj.getCommemorativeTicket());
                cat = cat.add(obj.getCat());
                trafficCard = trafficCard.add(obj.getTrafficCard());
                qrCodeTicket = qrCodeTicket.add(obj.getQrCodeTicket());
                faceTicketCcb = faceTicketCcb.add(obj.getFaceTicketCcb());
                incomeSubtotal = incomeSubtotal.add(obj.getIncomeSubtotal());
            }
        }

        sumViewCkOperatorsTicketRevenueClear.setReceivableOnewayReceivedClean(receivableOnewayReceivedClean.setScale(2,BigDecimal.ROUND_HALF_UP));
		sumViewCkOperatorsTicketRevenueClear.setReturnOnewayReceivedClean(returnOnewayReceivedClean.setScale(2,BigDecimal.ROUND_HALF_UP));
		sumViewCkOperatorsTicketRevenueClear.setSumOnewayReceivedClean(sumOnewayReceivedClean.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsTicketRevenueClear.setCountingTicket(countingTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsTicketRevenueClear.setDailyTicket(dailyTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsTicketRevenueClear.setCommemorativeTicket(commemorativeTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsTicketRevenueClear.setCat(cat.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsTicketRevenueClear.setTrafficCard(trafficCard.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsTicketRevenueClear.setQrCodeTicket(qrCodeTicket.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsTicketRevenueClear.setFaceTicketCcb(faceTicketCcb.setScale(2,BigDecimal.ROUND_HALF_UP));
        sumViewCkOperatorsTicketRevenueClear.setIncomeSubtotal(incomeSubtotal.setScale(2,BigDecimal.ROUND_HALF_UP));
        return sumViewCkOperatorsTicketRevenueClear;
    }

    @Override
    public void export(String startDate,String endDate,String operators,String lineCode,HttpServletResponse response) {

        List<ViewCkOperatorsTicketRevenueClear> records = listViewCkOperatorsTicketRevenueClear(startDate,endDate,operators,lineCode);
        InputStream excelTemplateIs = null;
        try {response.reset(); // 非常重要
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            final String fileName = URLEncoder.encode("运营商票务收入清分报表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");

            // 模板注意 用{} 来表示你要用的变量 如果本来就有"{","}" 特殊字符 用"\{","\}"代替
            // {} 代表普通变量 {.} 代表是list的变量

            excelTemplateIs = this.getClass().getResourceAsStream("/static/excel/template/export/ViewCkOperatorsTicketRevenueClearExcelTemplate.xlsx");

            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).registerConverter(new LocalDateTimeConverter()).registerConverter(new LocalDateConverter()).withTemplate(excelTemplateIs).build();
            WriteSheet writeSheet = EasyExcel.writerSheet("运营商票务收入清分报表").build();
            // 这里注意 入参用了forceNewRow 代表在写入list的时候不管list下面有没有空行 都会创建一行，然后下面的数据往后移动。默认 是false，会直接使用下一行，如果没有则创建。
            // forceNewRow 如果设置了true,有个缺点 就是他会把所有的数据都放到内存了，所以慎用
            // 简单的说 如果你的模板有list,且list不是最后一行，下面还有数据需要填充 就必须设置 forceNewRow=true 但是这个就会把所有数据放到内存 会很耗内存
            // 如果数据量大 list不是最后一行 参照另一个
            FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.FALSE).build();
            excelWriter.fill(records, fillConfig, writeSheet);
            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", startDate);
            map.put("endTime", endDate);
            excelWriter.fill(map, writeSheet);
            excelWriter.finish();

        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("导出运营商票务收入清分报表异常");
        } finally {
            if(excelTemplateIs != null){
                try {
                    excelTemplateIs.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }
    }
}
